package repository

import (
	"demo/internal/model"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type UserRepo struct {
	db *gorm.DB
}

func NewUserRepo(db *gorm.DB) *UserRepo {
	return &UserRepo{db}
}

func (r *UserRepo) Create(u *model.User) error {
	return r.db.Create(u).Error
}

func (r *UserRepo) FindByName(name string) (*model.User, error) {
	var u model.User
	err := r.db.Where("username = ?", name).First(&u).Error
	if err != nil {
		return nil, errors.Wrap(err, "find user by name")
	}
	return &u, nil
}

// FindByNickname 根据昵称模糊查询并分页
func (r *UserRepo) FindByNickname(nickname string, page, size int) ([]*model.User, int64, error) {
	var users []*model.User
	var total int64

	query := r.db.Model(&model.User{})
	if nickname != "" {
		query = query.Where("nickname LIKE ?", "%"+nickname+"%")
	}

	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, errors.Wrap(err, "count users")
	}

	err = query.Offset((page - 1) * size).Limit(size).Find(&users).Error
	if err != nil {
		return nil, 0, errors.Wrap(err, "find users")
	}

	return users, total, nil
}
